//
//  CheckBoxBar.swift
//  Game
//
//  Created by woniu on 2025/9/4.
//

import Foundation
import UIKit
import SnapKit

/// CheckBoxBar
/// 一个简单的单选 checkbox 组件（横向排列）
class CheckBoxBar: UIView {
    
	// 公共配置
	public var selectedBackgroundColor: UIColor = Colors.blue
    public var normalBackgroundColor: UIColor = Colors.blue.withAlphaComponent(0.10)
	public var selectedTextColor: UIColor = .white
    public var normalTextColor: UIColor = Colors.blue
    public var cornerRadius: CGFloat = 55*0.5
	public var itemSpacing: CGFloat = 15

	
	// 内部视图
	private let stack = UIStackView()
	private var buttons: [UILabel] = []
	private var options: [String] = []
	private(set) var selectedIndex: Int? = nil

	override init(frame: CGRect) {
		super.init(frame: frame)
		setup()
	}

	required init?(coder: NSCoder) {
		super.init(coder: coder)
		setup()
	}

	private func setup() {
		backgroundColor = .clear
		stack.axis = .horizontal
		stack.alignment = .center
		stack.distribution = .fillProportionally
		stack.spacing = itemSpacing
		addSubview(stack)
		stack.snp.makeConstraints { make in
			make.edges.equalToSuperview()
		}
	}
    
    public func getSelectedItem()->(index:Int,val:String)?{
        if let selectedIndex = selectedIndex{
            let lab = buttons[selectedIndex]
            let txt = lab.text ?? ""
            let index = lab.tag
            return (index,txt)
        }
        return nil
    }
    
    public func clear(){
        selectedIndex = nil
        for lab in buttons{
            updateLab(lab, selected: false)
        }
    }

	/// 设置选项（会清除已有）
	public func setOptions(_ opts: [String]) {
		// 清理
		for b in buttons { b.removeFromSuperview() }
		buttons.removeAll()
		options = opts

		for (i, t) in opts.enumerated() {
			let b = makeOptionButton(title: t, index: i)
			buttons.append(b)
			stack.addArrangedSubview(b)
			b.snp.makeConstraints { make in
				make.height.equalTo(55)
			}
		}
		// 默认未选中
		selectedIndex = nil
	}

	private func makeOptionButton(title: String, index: Int) -> UILabel {
		let itemLab = UILabel()
        itemLab.font = UIFont.boldSystemFont(ofSize: 25)
        itemLab.textAlignment = .center
        itemLab.text = title
        itemLab.circular(cornerRadius)
        itemLab.tag = index
        itemLab.isUserInteractionEnabled = true
        updateLab(itemLab, selected: false)
        let tap = UITapGestureRecognizer(target: self, action: #selector(onTap(_:)))
        itemLab.addGestureRecognizer(tap)
		return itemLab
	}

    @objc func onTap(_ deco:UITapGestureRecognizer){
        if let view = deco.view{
            select(index: view.tag)
        }
	}
    
    public func updateSlected(by title:String){
        for (i,lab) in buttons.enumerated(){
            let txt = lab.text ?? ""
            if txt == title{
                selectedIndex = i
                updateLab(lab, selected: true)
            }else{
                updateLab(lab, selected: false)
            }
        }
    }

	/// 选择指定下标（外部调用）
	public func select(index: Int) {
        for (i,lab) in buttons.enumerated(){
            if i == index{
                selectedIndex = i
                updateLab(lab, selected: true)
            }else{
                updateLab(lab, selected: false)
            }
        }
	}

	private func updateLab(_ lab: UILabel, selected: Bool) {
		if selected {
            lab.backgroundColor = selectedBackgroundColor
            lab.textColor = selectedTextColor
			
		} else {
            lab.backgroundColor = normalBackgroundColor
            lab.textColor = normalTextColor
		}
	}

	/// 获取当前选中项
	public func getSelected() -> (index: Int, title: String)? {
		guard let i = selectedIndex else { return nil }
		return (i, options[i])
	}
}
